package com.yunsom.testdemo.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Xbao
 * @description
 * @date 2022/5/27 15:14
 */
public class ServerSocketTest {

  public static void main(String[] args) {

    try {

      // 初始化服务端socket并且绑定9999端口
      ServerSocket serverSocket = new ServerSocket(9999);

      Socket client = serverSocket.accept();

      InputStream inputStream = client.getInputStream();

      DataInputStream dataInputStream =new DataInputStream(inputStream);

      while (true){

        byte b = dataInputStream.readByte();

        int len = dataInputStream.readInt();

        byte[] data =new byte[len -5];

        dataInputStream.readFully(data);

        String str =new String(data);

        System.out.println("获取的数据类型为："+b);

        System.out.println("获取的数据长度为："+len);

        System.out.println("获取的数据内容为："+str);

      }

//      //单客户端
//      //获取输入流,并且指定统一的编码格式
//      BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
//      //读取一行数据
//      String str;
//      //通过while循环不断读取信息，
//      while ((str = bufferedReader.readLine())!=null){
//        System.out.println(socket.getLocalAddress() + "--" + socket.getLocalSocketAddress());
//        System.out.println("客户端说：" + str);
//      }

      //      //多客户端（多线程）
//      //创建一个线程池
//      ExecutorService executorService = Executors.newFixedThreadPool(100);
//      while (true){
//        Socket socket = serverSocket.accept();
//        Runnable runnable = () -> {
//            try {
//              //获取输入流
//              BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//              while (true){
//                //读取一行数据
//                String str = bufferedReader.readLine();
//                //输出打印
//                if(null != str){
//                  System.out.println("客户端说：" + str);
//                }
//              }
//            } catch (IOException e) {
//              e.printStackTrace();
//            }
//        };
//        executorService.submit(runnable);
//      }

    }catch (Exception e) {
      e.printStackTrace();
    }

  }

}
